package com.jy.project.ex;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageException;
import com.jy.project.util.ServiceResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Iterator;
import java.util.List;

@RestControllerAdvice
@Slf4j
public class BizExceptionAdvice {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(Exception ex) {
        if (ex instanceof BizException) {
            BizException biz=(BizException)ex;
            if (biz.getCode().equals("-1")){
                return ServiceResultUtils.failure(biz.getValue());
            }
            return  ServiceResultUtils.failure(biz.getCode(),biz.getValue());
        }
        if (ex instanceof BindException){
            BindException validException=(BindException)ex;
            List<FieldError> fieldErrors = validException.getFieldErrors();
            Iterator<FieldError> iterator = fieldErrors.iterator();
            while (iterator.hasNext()){
                String defaultMessage = iterator.next().getDefaultMessage();
                return  ServiceResultUtils.failure(defaultMessage.toString());
            }
        }
        if (ex instanceof PageException){
            PageException pageException=(PageException)ex;
            return  ServiceResultUtils.failure(pageException.getMessage());
        }


        ex.printStackTrace();
        return ServiceResultUtils.failure("未知错误,请重新再试");
    }

}
